﻿using System;
using System.Text;
using CID.Execution.Support.Scripting;
using CID.Execution.Support.TemplateHandling;
using System.Collections.Generic;
using CID.Execution.Support.Information;
using System.Linq;

namespace CID.Execution.Agent
{
    class DeactivationScriptExecuter : BaseScriptExecuter<LocationDeactivationScript, DeactivationScriptStep>
    {
        public DeactivationScriptExecuter(LocationDeactivationScript script) : base(script) { }

        protected override void ExecuteStep(DeactivationScriptStep step, StringBuilder detailsBuilder)
        {
            AppendMessage(detailsBuilder, "Started deactivation of Component: {0}", step.Component.Name);

            var templateHandler = TemplateHandlerFactory.Instance.CreateTemplateHandler(step.Template.Type);
            templateHandler.ExecuteTemplate(step.Template, step.ParameterValues, GetGeneralAdditionalParameterValues().Concat(GetSpecificAdditionalParameterValues(step)), step.TargetServers, detailsBuilder);

            AppendMessage(detailsBuilder, "Ended deactivation of Component: {0}", step.Component.Name);
        }

        private IEnumerable<ParameterValueInfo> GetSpecificAdditionalParameterValues(DeactivationScriptStep step)
        {
            var result = new List<ParameterValueInfo>();
            result.Add(ParameterValueInfo.CreateAdditionalParameterValue(ParameterValueInfo.ReservedParameterNames.ComponentName, step.Component.Name));
            return result;
        }

        protected override void OnExecutionStarted(LocationDeactivationScript script, StringBuilder detailsBuilder)
        {
            AppendMessage(detailsBuilder, "Started Deactivation");
        }

        protected override void OnExecutionEnded(LocationDeactivationScript script, string details, bool error)
        {
            var controllerProxy = ControllerServiceProxyFactory.Create();
            try
            {
                controllerProxy.NotifyDeactivationCompleted(script.DeploymentUniqueIdentifier, script.LocationId, details, error);
            }
            catch (Exception ex)
            {
                NotifyControllerCommnunicationError(ex);
            }
            finally
            {
                ControllerServiceProxyFactory.Dispose(controllerProxy);
            }

        }
    }
}
